#include <stdlib.h>
#include <stdio.h>
#include <WinSock2.h>
#include <Ws2tcpip.h>
#include "Common.h"
#pragma comment(lib, "Common.lib")
#pragma comment(lib, "ws2_32.lib")

#define ROOTUSERID -2

SOCKET g_listenSocket;
int totalUser = 0;

void init(void) {
	//network
	WSAData wsaData;
	if( WSAStartup(MAKEWORD(2,2), &wsaData) != 0 ) {
		error("bad startup");
		return;
	}
}

TUserInfo* rootUser = NULL;

void waiting(void) {
	SOCKET acceptSocket;
	char buf[MAXBUFFSIZE];
	memset(buf, 0, MAXBUFFSIZE);
	while (true) {
		acceptSocket = accept(g_listenSocket, NULL, NULL);
		if (acceptSocket == INVALID_SOCKET) {
			error("accept failed");
			return;
		}
		int recvBytes = recv(acceptSocket, buf, MAXBUFFSIZE, 0);
		if (recvBytes < 0) {
			error("recv failed");
			closesocket(acceptSocket);
			return;
		}
		else if (recvBytes == 0)
			break;
		buf[recvBytes] = 0;
		TOperationInfo opInfo;
		sscanf(buf, "%d %d", &opInfo.op, &opInfo.val);
		bool opRetVal = false;
		switch (opInfo.op) {
		case USER_CONNECT:
			if (addUser(rootUser, opInfo.val, &rootUser))
				++totalUser;
			opRetVal = true;
			break;
		case USER_RELEASE:
			if (deleteUser(rootUser, opInfo.val, &rootUser))
				--totalUser;
			opRetVal = true;
			break;
		case USER_GETNODE:
			opRetVal = find(rootUser, opInfo.val);
			break;
		}

		memset(buf, 0, MAXBUFFSIZE);
		sprintf(buf, "%d#", opRetVal);
		send(acceptSocket, buf, strlen(buf), 0);
		closesocket(acceptSocket);
	}
}

void cleanup(void) {
	closesocket(g_listenSocket);
	WSACleanup();
}

int main(void)
{
	init();

	createListenSocket(PORT2, &g_listenSocket, true);

	waiting();

	cleanup();

	return 0;
}
